package com.wedimob.scrapper.network;

import java.net.URI;
import java.util.concurrent.Callable;

import org.jsoup.Connection.Response;

import com.wedimob.scrapper.data.Content;

/**
 * Future response container.
 * 
 * @author melouadi
 * 
 */
class DocumentResponse implements Callable<Content> {

	/**
	 * connection strategy.
	 */
	private ConnectionStrategy strategy;

	/**
	 * source.
	 */
	private URI uri;

	/**
	 * reader.
	 */
	private ContentReader reader;

	/**
	 * minimal constructor.
	 * 
	 * @param aStrategy
	 *            connexion strategy
	 * @param aReader
	 *            reader
	 * @param aUri
	 *            source
	 */
	public DocumentResponse(final ConnectionStrategy aStrategy,
			final ContentReader aReader, final URI aUri) {
		this.uri = aUri;
		this.reader = aReader;
		this.strategy = aStrategy;
	}

	@Override
	public Content call() throws Exception {

		try {
			Response response = null;
			String url = uri.toASCIIString();
			boolean isLocal = !url.contains("://") || url.contains("file://");
			if (isLocal) {
				throw new RuntimeException(uri + " is not a remote adress");
			}

			int nbAttempt = 0;
			do {
				nbAttempt++;
				try {
					response = strategy.get(url, reader.getTimeout());
					return new Content(uri, response);
				} catch (Throwable e) {
					if (nbAttempt >= reader.getMaxRetry()) {
						return new Content(uri, e);
					} else {
						Thread.sleep(ContentReader.RETRY_DELAY);
					}
				}
			} while (nbAttempt < reader.getMaxRetry());
		} catch (Throwable e) {
			return new Content(uri, e);
		}
		return null;
	}
}